package ch.ffhs.links_library.login;

import javax.ejb.Stateful;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

import ch.ffhs.links_library.entities.User;
import javax.ejb.Remove;


@Stateful
@Name("authenticator")
public class Authenticator implements AuthenticatorLocal
{
    @Logger private Log log;

    @In Identity identity;
    @In Credentials credentials;
    
    /* DB Context to get user */
	@PersistenceContext
	private EntityManager em;
	
    /*
     * return true if the authentication was successful, 
     * false otherwise
     */
	
    /* (non-Javadoc)
	 * @see ch.ffhs.links_library.login.AuthenticatorLocal#authenticate()
	 */
    public boolean authenticate()
    {
    	log.info("authenticating {0}", credentials.getUsername());
    	if("".equals(credentials.getUsername()) || "".equals(credentials.getPassword())) {
    		log.info("Username or password empty");
    		return false;
    	}
    	//Query database and make sure that the user is returned correctly (compare username)
    	User u = (User) em.createNamedQuery("findUserWithName").setParameter("username", credentials.getUsername()).getSingleResult();
    	if(!u.getUsername().equals(credentials.getUsername())) {
    		log.error("User not found");
    		return false;
    	}
    		
    	
    	//Check that the password is correct, assign 
    	if(credentials.getPassword().equals(u.getPassword())) {
    		if(u.getAdmin() == 0) {
    			identity.addRole("user");
    			log.info("Login as a user");
    		} else {
    			identity.addRole("admin");
    			log.info("Login as an administrator");
    		}
    		return true;
    	}
    	
    	return false;
    }

	@Remove
	@Destroy
	public void remove() {
	}

}
